#!/usr/bin/python

# ARRss is an RSS parser for torrents and the people who pirate them
# It downloads .torrent files for a given rss feed/regex and tracks the last episode/date

import feedparser
import sys
import re
import os
from ConfigParser import ConfigParser
import urllib

def getLastEpisode( settings, arrss_settings):
    name = re.compile(settings['NAME_RE'])
    date = re.compile(settings['DATE_RE'])
    last = int( settings['LAST'] )
    downloadDates = []

    parser = feedparser.parse( settings['FEED'] )

    for item in parser['items']:
        if name.search( item[settings['NAME_LOC']] ):
            d = date.search(item[settings['DATE_LOC']])

            # compare concatenation of date or season
            # date only works in ymd order
            current = int( tupleToString(d.groups()) )
            if current > last:
                download( item[settings['FILE_LOC']], item[settings['NAME_LOC']], arrss_settings )
                downloadDates.append(int(current))
    return downloadDates

def tupleToString(tup):
    return reduce( lambda x, y: x+y, tup )

def download(url, name, arrss_settings):
    remotefp = urllib.urlopen( url )
    curl = remotefp.read()
    remotefp.close()

    #print url
    #print name
    print arrss_settings['TORRENT_HOME']
    dest = arrss_settings['TORRENT_HOME'] + "/" + name
    out = open(dest, "w")
    out.write(curl)
    out.close()

def main():
    settings = {'FEED':0, 'NAME_RE':0, 'LAST':0, 'DATE_RE':0, 'FILE_LOC':0,'DATE_LOC':0,'NAME_LOC':0}
    arrss_settings = {'TORRENT_HOME': 0}
    

    rcfile = os.getenv('HOME') + '/.arrss'
    fp = open(rcfile)
    conf = ConfigParser()
    conf.readfp(fp)
    arrss_settings['TORRENT_HOME'] = conf.get('global', 'TORRENT_HOME')
    fp.close()
    

    # go through each show and it's feed.  maybe add arrss config option?
    for show in conf.sections():
        if (show != 'global'):
            for s in settings:
                settings[s] = conf.get(show, s);

            downloadDates = getLastEpisode( settings, arrss_settings ) 

            #update rc file with last dates
            if len(downloadDates) > 0:
                downloadDates.sort()
                downloadDates.reverse()
                conf.set(show, "LAST", downloadDates[0])

    fp = open(rcfile, "w+")
    conf.write(fp)
    fp.close() 


if __name__ == '__main__':
    sys.exit( main() )
